package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.AccounLoginInfo;
import com.zb.entity.ZjAccountBalanceAdjust;
import com.zb.entity.ZjFactory;
import com.zb.entity.ZjFactoryAccountBalance;
import com.zb.mapper.ZjAccountBalanceAdjustMapper;
import com.zb.service.ZjAccountBalanceAdjustService;
import com.zb.service.ZjFactoryAccountBalanceService;
import com.zb.service.ZjFactoryRechargeService;
import com.zb.service.ZjFactoryService;
import com.zb.vo.FactoryBalanceAdjustVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 厂商余额调整表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-02-27
 */
@Service
public class ZjAccountBalanceAdjustServiceImpl extends ServiceImpl<ZjAccountBalanceAdjustMapper, ZjAccountBalanceAdjust> implements ZjAccountBalanceAdjustService {
    @Resource
    private ZjFactoryService factoryService;
    @Resource
    private ZjFactoryAccountBalanceService factoryAccountBalanceService;
    @Resource
    private ZjFactoryRechargeService factoryRechargeService;

    // 保存商家调整余额
    @Override
    public void save(AccounLoginInfo loginInfo, Long factoryId, FactoryBalanceAdjustVo adjustVo) {
        ZjFactory factory = factoryService.getById(factoryId);
        Assert.notNull(factory, "商家参数[ " + factoryId + " ]的数据不存在，无法调整余额");
        Assert.isTrue(factory.getStatus() == 2,
                factory.getStatus() == 1? "商家待审核中，不允许调整余额" :
                factory.getStatus() == 3? "商家已被审核驳回，不允许调整余额" : "商家已被禁用，不允许调整余额"
                );
        ZjFactoryAccountBalance balance = factoryAccountBalanceService.getById(factoryId);
        ZjAccountBalanceAdjust adjust = new ZjAccountBalanceAdjust();
        BeanUtil.copyProperties(adjustVo, adjust);
        adjust.setId(IdWorker.getId());
        adjust.setFactoryId(factoryId);
        adjust.setCurrentAccountBalance(balance.getMoney().subtract(balance.getFreezeMoney()));
        this.save(adjust);

        if (adjustVo.getAdjustMode() == 1) {
            balance.setMoney(balance.getMoney().add(adjustVo.getAdjustMoney()));
        } else {
            balance.setMoney(balance.getMoney().subtract(adjustVo.getAdjustMoney()));
        }
        factoryAccountBalanceService.updateById(balance);
        factoryRechargeService.save(loginInfo, factoryId, adjustVo);
    }
}
